package gw.com.android.utils;

import android.text.TextUtils;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Collection;
import java.util.TreeMap;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.Https;
import gw.com.jni.library.terminal.GTSConst;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.util.AESCrypto;
import www.com.library.util.AESCrypto3;
import www.com.library.util.JsonUtil;
import www.com.library.util.Md5;

/**
 * Created by aries.zhan on 2018/4/20.
 */

public class OpenApi {
    public static final String CLICK_PUSH_DETAIL_CENTERLIST = "CenterList";
    public static final String CLICK_PUSH_DETAIL_NOTICEBOARD = "NoticeBoard";

    /**
     * 自动push API
     */
    public static void pushDataByEvent(String eventIndex, String alias) {
        final Https https = new Https("https://openapi.hx9999.com/tools/");
        https.addParam("service", "Pushsystem.pushDataByEvent");
        https.addParam("eventIndex", eventIndex);
        https.addParam("terminal", "android");
        try {
            https.addParam("loginAccount", AESCrypto3.Encrypt(alias));
            String sign = "";
            Collection<String> signs = new TreeMap<>(https.getParam()).values();
            for (String str : signs) {
                sign += str;
            }
            https.addParam("sign", Md5.md5((sign + BuildConfig.openApiSignKey).getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        https.get(null);
    }

    /**
     * 获取消息详情
     *
     * @param type 点击类型(CenterList/NoticeBoard)
     */
    public void getPushInfoDetail(String detailId, String type, String extend, final HttpCallback<String> callback) {
        Https https = new Https("https://openapi.hx9999.com/tools/");
        String service = "Pushsystem.getDetail";
        https.addParam("service", service);
        https.addParam("detailId", detailId);
        https.addParam("type", type);
        https.addParam("extend", extend == null ? "" : extend);
        https.addParam("alias", GTConfig.instance().getDefaultJpushAlias());
        String sign = "";
        Collection<String> signs = new TreeMap<>(https.getParam()).values();
        for (String str : signs) {
            sign += str;
        }
        https.addParam("sign", Md5.md5((sign + BuildConfig.openApiSignKey).getBytes()));
        https.get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                if (code != 200 || !JsonUtil.isJsonData(result)) {
                    callback.onFailure(null);
                } else {
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        if (resultJson.getInt("ret") == 200) {
                            callback.onSuccess(result);
                        } else {
                            callback.onFailure(null);
                        }
                    } catch (JSONException e) {
                        callback.onFailure(null);
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                callback.onFailure(null);
            }
        });
    }

    /**
     * 登陆成功后，获取token
     */
    public static void generateToken(final int counter) {
        if (counter >= 3) {
            return;
        }
        int accountType = GTConfig.instance().getAccountType();
        String type;
        if (accountType == GTConfig.ACC_TYPE_REAL) {
            type = "real";
        } else if (accountType == GTConfig.ACC_TYPE_DEMO) {
            type = "demo";
        } else {
            return;
        }
        String url = "https://openapi.hx9999.com/tools/";
        Https https = new Https(url)
                .addParam("service", "members.getToken")
                .addParam("login", AESCrypto.encrypt(GTConfig.instance().mCurName))
                .addParam("platform", "GTS2")
                .addParam("type", type);
        String sign = "";
        Collection<String> signs = new TreeMap<>(https.getParam()).values();
        for (String str : signs) {
            sign = sign.concat(str);
        }
        https.addParam("sign", Md5.md5((sign + BuildConfig.openApiSignKey).getBytes()));
        https.get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    GTConfig.instance().mOpenApiToken = jsonObject.optString("data");
                    if (!TextUtils.isEmpty(GTConfig.instance().mOpenApiToken)) {
                        return;
                    }
                } catch (JSONException e) {
                    Logger.e(e);
                }
                generateTokenDelay(counter + 1, 2001);
            }

            @Override
            public void onFailure(Request request, IOException e) {
                generateTokenDelay(counter + 1, 2000);
            }
        });
    }

    private static void generateTokenDelay(final int counter, long delay) {
        AppMain.getApp().getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                generateToken(counter);
            }
        }, delay);
    }

    /**
     * 账号 激活或者未激活
     */
    public static void isAccountActive() {
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
            return;
        }
        final String account = GTConfig.instance().mCurName;
        if (TextUtils.isEmpty(account)) {
            Logger.i("isAccountActive", " account is empty");
            return;
        }
        Logger.i("isAccountActive", "request now : " + account);
        String url = "https://openapi.hxfx.com/tools/";
        Https https = new Https(url)
                .addParam("service", "open.isActivate")
                .addParam("login", account)
                .addParam("company_id", String.valueOf(ConfigUtil.instance().mConfigObject.optInt(ConfigType.COMPANY_ID_TAG)))  //公司id 9999:2；sv:9
                .addParam("platform", "GTS2");
        String sign = "";
        Collection<String> signs = new TreeMap<>(https.getParam()).values();
        for (String str : signs) {
            sign = sign.concat(str);
        }
        https.addParam("sign", Md5.md5((sign + "abc123").getBytes()));
        https.get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                Logger.i("isAccountActive", "request onSuccess");
                handleAccountActive(account, result);
            }

            @Override
            public void onFailure(Request request, IOException e) {
                Logger.e("isAccountActive", e);
            }
        });
    }

    private static void handleAccountActive(String account, String result) {
        try {
            JSONObject json = new JSONObject(result);
            JSONObject dataJson = json.optJSONObject("data");
            if (dataJson != null) {
                if (dataJson.optInt("is_ok") == 1 && dataJson.has("is_activate")) {
                    boolean isActivate = dataJson.getBoolean("is_activate");
                    Logger.i("isAccountActive", "account is active : " + isActivate);
                    GTConfig.instance().addAccountActiveState(account, isActivate);
                    RxBus.getInstance().post(GTSConst.REPLY_RFRESH_ADS, "");
                    RxBus.getInstance().post(GTSConst.REPLY_ACCOUNT_IS_ACTIVE, "");
                    return;
                }
            }
        } catch (JSONException e) {
            Logger.e("isAccountActive", e);
        }
        Logger.i("isAccountActive", "result = " + result);
    }

    /**
     * CPS转移开关
     */
    public static void isStartTransfer(final HttpCallback<Boolean> callback) {
        Logger.i("isStartTransfer", "request");
        String url = "https://openapi.hx9999.com/tools/";
        Https https = new Https(url);
        https.addParam("service", "App.getActionParam");
        https.addParam("applicationId", "com.gwtsz.gts2.hx");
        https.addParam("channel", "android_transfer");
        https.addParam("version", "300");
        /*String sign = "";
        Collection<String> signs = new TreeMap<>(https.getParam()).values();
        for (String str : signs) {
            sign = sign.concat(str);
        }
        https.addParam("sign", Md5.md5((sign + BuildConfig.openApiSignKey).getBytes()));*/
        https.get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                boolean state = false;
                Logger.i("isStartTransfer", "success result = " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject dataJson = jsonObject.optJSONObject("data");
                    if (dataJson != null) {
                        String isOpen = dataJson.optString("is_open");
                        state = "Y".equals(isOpen);
                        Logger.i("isStartTransfer", "success state = " + state);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (callback != null) {
                    callback.onSuccess(state);
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                Logger.i("isStartTransfer", "error " + e.getMessage());
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

    /**
     * 9999 账号分流
     */
    public static void accountDistribute(String account, final HttpCallback<String> callback) {
        Logger.i("accountDistribute", "request account = " + account);
        String url = "https://openapi.topopenapi.com/tools/";
        Https https = new Https(url);
        https.addParam("service", "open.getRegisterType");
        https.addParam("login", account);
        String sign = "";
        Collection<String> signs = new TreeMap<>(https.getParam()).values();
        for (String str : signs) {
            sign = sign.concat(str);
        }
        https.addParam("sign", Md5.md5((sign + "abc123").getBytes()));
        https.get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                //  {"ret":200,"data":{"status":1,"company_name":"sv","actmsg":""},"msg":""}     sv,8bx,ft,hk
                String target = null;
                Logger.i("accountDistribute", "success result = " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject dataJson = jsonObject.optJSONObject("data");
                    if (dataJson != null) {
                        target = dataJson.optString("company_name", null);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (callback != null) {
                    callback.onSuccess(target);
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                Logger.i("accountDistribute", "error " + e.getMessage());
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

    /**
     * 请求是否显示数字货币的开关
     */
    public static void requestDigitalCurrency(final HttpCallback<Boolean> callback) {
        Logger.i("requestDigitalCurrency", "request");
        String url = "https://openapi.hx9999.com/tools/";
        Https https = new Https(url);
        https.addParam("service", "App.getActionParam");
        https.addParam("applicationId", "com.gwtsz.gts2.ft");
        https.addParam("version", "120");//CPS开关有对应的包名和版本号的区分
        https.addParam("channel", "digital_currency");
        https.get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                boolean state = true;
                Logger.i("requestDigitalCurrency", "success result = " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject dataJson = jsonObject.optJSONObject("data");
                    if (dataJson != null) {
                        String isOpen = dataJson.optString("is_open");
                        state = "Y".equals(isOpen);
                        Logger.i("requestDigitalCurrency", "success state = " + state);
                    }
                } catch (JSONException e) {
                    Logger.e("requestDigitalCurrency", e);
                }
                if (callback != null) {
                    callback.onSuccess(state);
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                Logger.i("requestDigitalCurrency", "error " + e.getMessage());
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

}
